#include <iostream>
#include <memory>
#include <string>

#include <grpc++/grpc++.h>

#include "greetings.grpc.pb.h"

using grpc::Channel;
using grpc::ClientContext;
using grpc::Status;

using greetings::Greeter;
using greetings::HelloReply;
using greetings::HelloRequest;

class GreeterClient
{
public:
    GreeterClient(std::shared_ptr<Channel> channel) : stub_(Greeter::NewStub(channel)) {}
    std::string SayHello(const std::string &user)
    {
        HelloRequest request;
        request.set_name(user);
        HelloReply reply;
        ClientContext context;
        Status status = stub_->SayHello(&context, request, &reply);

        // Act upon its status.
        if (status.ok())
        {
            return reply.message();
        }
        else
        {
            std::cout << status.error_code() << ": " << status.error_message() << std::endl;
            return "gRPC failed";
        }
    }

private:
    std::unique_ptr<Greeter::Stub> stub_;
};

void InterativeGRPC()
{
    GreeterClient greeter(grpc::CreateChannel("localhost:8080", grpc::InsecureChannelCredentials()));
    while (true)
    {
        std::string user;
        std::cout << "Please enter your user name:" << std::endl;
        // std::cin >> user;
        std::getline(std::cin, user);
        std::string reply = greeter.SayHello(user);
        if (reply == "gRPC failed")
        {
            std::cout << "gRPC failed" << std::endl;
        }
        std::cout << "gRPC returned: " << std::endl;
        std::cout << reply << std::endl;
    }
}

int main()
{

    InterativeGRPC();
    return 0;
}
